﻿using D.AT.Dto;
using D.AT.Events;
using D.AT.Extensions;
using D.AT.HttpUtil;
using D.AT.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.Button;

namespace D.AT
{
    public partial class FrmBasicCheck : Form
    {
        public FrmBasicCheck()
        {
            InitializeComponent();
        }

        private void FrmBasicCheck_Load(object sender, EventArgs e)
        {

        }

        #region 更换环境

        private EnvSettingEntity envSettingEntity = null;
        private async void btnConn_Click(object sender, EventArgs e)
        {
            try
            {
                envSettingEntity = this.cboEnv.SelectedItem as EnvSettingEntity;
                if (envSettingEntity != null)
                {
                    var initRes = await ResetFreeSql(envSettingEntity);
                    if (initRes == 0)
                    {// 成功、重新加载所有数据 

                        this.btnConn.Enabled = false;
                    }
                    else if (initRes == 1)
                    {// spc连接失败
                        MessageBox.Show("SPC数据库连接异常");
                    }
                    else if (initRes == 2)
                    {// mes连接失败
                        MessageBox.Show("MES数据库连接异常");
                    }
                    else
                    {// -1 异常
                        MessageBox.Show("数据库连接异常");
                    }
                }
                else
                {
                    MessageBox.Show("请选择数据库链接");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("数据库连接异常");
            }
        }
        private void cboEnv_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.btnConn.Enabled = true;
        }
        public async Task<int> ResetFreeSql(EnvSettingEntity envSettingEntity)
        {
            // 拼接连接字符串(service Name 不行)
            var spcConnStr = string.Empty;
            var mesConnStr = string.Empty;

            if (envSettingEntity.SPCSidOrServiceName == "SID")
            {// SID
                spcConnStr = $"User ID={envSettingEntity.SPCAccount};Password={envSettingEntity.SPCPwd};Data Source=(DESCRIPTION = (ADDRESS_LIST= (ADDRESS = (PROTOCOL = TCP)(HOST = {envSettingEntity.SPCIp})(PORT = {envSettingEntity.SPCPort}))) (CONNECT_DATA = ({envSettingEntity.SPCSidOrServiceName} = {envSettingEntity.SPCSid})))";
                //spcConnStr = $"user id={envSettingEntity.SPCAccount};password={envSettingEntity.SPCPwd}; data source={envSettingEntity.SPCIp}:{envSettingEntity.SPCPort}:{envSettingEntity.SPCSid};Pooling=true;Min Pool Size=1 ";
            }
            else
            {// Service Name
                spcConnStr = $"user id={envSettingEntity.SPCAccount};password={envSettingEntity.SPCPwd}; data source={envSettingEntity.SPCIp}:{envSettingEntity.SPCPort}/{envSettingEntity.SPCSid};Pooling=true;Min Pool Size=1 ";
            }

            if (envSettingEntity.MESSidOrServiceName == "SID")
            {// SID
                mesConnStr = $"User ID={envSettingEntity.MESAccount};Password={envSettingEntity.MESPwd};Data Source=(DESCRIPTION = (ADDRESS_LIST= (ADDRESS = (PROTOCOL = TCP)(HOST = {envSettingEntity.MESIp})(PORT = {envSettingEntity.MESPort}))) (CONNECT_DATA = ({envSettingEntity.MESSidOrServiceName}= {envSettingEntity.MESSid})))";
                //mesConnStr = $"user id={envSettingEntity.MESAccount};password={envSettingEntity.MESPwd}; data source={envSettingEntity.MESIp}:{envSettingEntity.MESPort}:{envSettingEntity.MESSid};Pooling=true;Min Pool Size=1 ";
            }
            else
            {// Service Name
                mesConnStr = $"user id={envSettingEntity.MESAccount};password={envSettingEntity.MESPwd}; data source={envSettingEntity.MESIp}:{envSettingEntity.MESPort}/{envSettingEntity.MESSid};Pooling=true;Min Pool Size=1 ";
            }

            // 初始化DB
            return await OrmFactory.AddFreeSql(envSettingEntity.Name, mesConnStr, spcConnStr);
        }
        #endregion

        #region 开始发送

        private async void btnStart_Click(object sender, EventArgs e)
        {
            // 获取需要建Chart的数据，dc item , area , subfolder , dcsid，eqpid，ruleobjecid
            var fabList = await OrmFactory.SpcOracle.Select<SPCFabEntity>().ToListAsync();
            var ruleEntities = await OrmFactory.SpcOracle.Select<SPCRuleEntity>().Where(m => m.RULE_STATUS == "Active").ToListAsync();
            var ldsList = await OrmFactory.SpcOracle.Select<SPCLdsEntity>().ToListAsync();
            var deparmentList = await OrmFactory.SpcOracle.Select<SPCDeparmentEntity>().Where(m => m.DATA_STATUS == "Active").ToListAsync();
            var chamebrList = await OrmFactory.MesOracle.Select<MESChamberEntity>().ToListAsync();
            var dcItemList = await OrmFactory.MesOracle.Select<MESDcItemEntity>()
                                            .Where(m => !m.DCITEM_NAME.Contains("W_") && !m.DCITEM_NAME.Contains("L_"))
                                            .Distinct()
                                            .ToListAsync();

            var holdList = await OrmFactory.SpcOracle.Select<SPCHoldEntity>().ToListAsync();

            var ldsEntity = ldsList.FirstOrDefault();
            var contextKeyList = await OrmFactory.SpcOracle.Select<SPCContextKeyEntity>().Where(m => m.COLLECT_TYPE == ldsEntity.COLLECT_TYPE && m.KEY_TYPE == 0).ToListAsync();
            var folderList = await OrmFactory.SpcOracle.Select<SPCSubFolderEntity>().Where(m => m.LDS_ID == ldsEntity.ID).OrderBy(m => m.SORT).ToListAsync();

            var folder = folderList.Where(m => m.NAME == "SYSTEM" && m.PARENT_ID == 0).FirstOrDefault();
            if (folder == null)
            {// 新增Folder,在加subFolder

            }
            // 获取子folder 
            var subFolderId = folderList.Where(m => m.NAME == "Scenario-1" && m.PARENT_ID == folder.ID).FirstOrDefault();


            //await CreateJob(fabList[0].ID, ldsEntity, folderId, deparmentId);
        }
        #endregion
        private async Task CreateJob(string fabId, SPCLdsEntity ldsEntity, string subFolderId, string deparmentId)
        {
            if (envSettingEntity == null)
            {
                MessageBox.Show("请选择环境."); return;
            }
            var chaartName = "基础数据校验-1-By Wafer建Chart-送同一片Wafer";
            var chartName = "基础数据校验-2-By Wafer建Chart-送多片Wafer";


            // 组装数据
            //var jobAddDto = BuildJob(fabId, ldsEntity, subFolderId,);

            // 发送数据
            //var url = $"http://{envSettingEntity.Ip}:{envSettingEntity.Port}/mycim-spc-service/v1/rt-job/add";
            //var res = await HttpClientHelper.HttpPostAsync<JobAddResponseDto>(url, ServiceLocator.TimeOut, jobAddDto);
            //// 统计结果
            //if (res.code == 200)
            //{
            //}
            //else if (res.code == 5000)
            //{// {"code":5000,"message":"JobNameExist","data":null}
            //}
            //else
            //{

            //}
        }

        private List<KeyValues> keyValueList = new List<KeyValues>()
        {
            new KeyValues() { Key = "Area", Value = "SYSTEM",ColumnIndex = 3 },
            new KeyValues() { Key = "ProcessEquipment", Value = "*",ColumnIndex = 11 },
            new KeyValues() { Key = "DCSID", Value = "",ColumnIndex = 29 }
        };

        private JobAddRequestDto BuildJob(long fabId, SPCLdsEntity ldsEntity, string subFolderId, long deparmentId, string chartName, string edcLevel, bool autoCreatedSubJob, bool onlySubjob,
            List<KeyValues> keyValueList, ScreenConfig screenConfig, Outlier outlier, ChartTypeLimit xbar, ChartTypeLimit trend, ChartTypeLimit r, ChartTypeLimit s,
            List<string> jobExcludeValueList, List<SPCHoldEntity> holdList, List<SPCRuleEntity> ruleEntities)
        {
            JobAddRequestDto jobAddDto = new JobAddRequestDto();

            #region 封装建Char对象

            jobAddDto.basicInfo = new BasicInfo()
            {
                ldsId = ldsEntity.ID.ToString(),
                spcFolderId = subFolderId,
                jobName = chartName,
                fabObjectId = fabId,
                moduleGroupId = deparmentId,
                edcLevel = edcLevel,
                controlStatus = "SPC_CONTROL",
                jobStatus = "ACTIVE",
                autoCreatedSubJob = autoCreatedSubJob,
                onlySubjob = onlySubjob,
                normalizaTionModelEnum = "NOTNORMALIZATION",
                movingChartReset = "2024-01-01 00:00:00",
                collectionIntervalOccurs = false,
                inlineType = ldsEntity.COLLECT_TYPE,
                keyChart = true,
                alarmMailTypes = new List<string>() { "ALARM_OCCURS" },
                subJob = false,
                matchingInherit = false,
                autoSubJobInherit = false,
                mailTemplateInherit = false,
                collectionIntervalInherit = true,
                collectionIntervalTemplateInherit = false,
                subJobInherit = new SubJobInherit(),
                chartDisplayInherit = true,
                displayType = "1",
                showGraphics = "",
                effectiveDate = "2024-01-01 00:00:00",
                dataType = "Variable",
                gradeAlarmId = "",
                mailTemplate = "",
                mailChartPointNum = 25,
                mailTo = new MailTo() { groupIds = new List<string>(), userIds = new List<string>() },
                mailCc = new MailCc() { groupIds = new List<string>(), userIds = new List<string>() },
                collectionIntervalMailTo = null,
                collectionIntervalMailCc = null,
            };
            jobAddDto.jobContextKeySaveRequests = new List<JobContextKeySaveRequests>();
            foreach (var item in keyValueList)
            {
                jobAddDto.jobContextKeySaveRequests.Add(new JobContextKeySaveRequests() { columnIndex = item.ColumnIndex, value = item.Value });
            }
            jobAddDto.jobExcludeValueList = jobExcludeValueList;

            jobAddDto.chartInfo = new ChartInfo()
            {
                unit = "-",
                outlier = outlier,
                chartTypes = new List<string>() { "XBAR", "TREND", "R", "S" },
                chartConfigs = new List<ChartConfigsItem>()
                    {
                        new ChartConfigsItem()
                        {
                            chartType="XBAR",
                            controlConfig = new ControlConfig()
                            {
                                limitType =  xbar.ControlLimitType,
                                cl= xbar.CL,
                                lcl=  xbar.LCL,
                                ucl=  xbar.UCL,
                                clDisable= false,
                                lclDisable= false,
                                uclDisable= false
                            },
                            specConfig = new SpecConfig()
                            {
                                limitType = xbar.SpecLimitType ,
                                target = xbar.Target,
                                lsl= xbar.LSL,
                                usl= xbar.USL,
                                lslDisable= false,
                                targetDisable= false,
                                uslDisable=false,
                            },
                             screenConfig = screenConfig,
                             warningLimit =xbar.WarningLimit,
                        },
                        new ChartConfigsItem()
                        {
                            chartType="TREND",
                            controlConfig = new ControlConfig()
                            {
                                limitType =  trend.ControlLimitType,
                                cl= trend.CL,
                                lcl=  trend.LCL,
                                ucl=  trend.UCL,
                                clDisable= false,
                                lclDisable= false,
                                uclDisable= false
                            },
                            specConfig = new SpecConfig()
                            {
                                limitType = trend.SpecLimitType ,
                                target = trend.Target,
                                lsl= trend.LSL,
                                usl= trend.USL,
                                lslDisable= false,
                                targetDisable= false,
                                uslDisable=false,
                            },
                             screenConfig = screenConfig,
                               warningLimit =trend.WarningLimit,
                        },
                        new ChartConfigsItem()
                        {
                            chartType="R",
                            controlConfig = new ControlConfig()
                            {
                                limitType =  r.ControlLimitType,
                                cl= r.CL,
                                lcl=  r.LCL,
                                ucl=  r.UCL,
                                clDisable= false,
                                lclDisable= false,
                                uclDisable= false
                            },
                            specConfig = new SpecConfig()
                            {
                                limitType = r.SpecLimitType ,
                                target = r.Target,
                                lsl= r.LSL,
                                usl= r.USL,
                                lslDisable= false,
                                targetDisable= false,
                                uslDisable=false,
                            },
                             screenConfig = screenConfig,
                               warningLimit =r.WarningLimit,
                        },
                        new ChartConfigsItem()
                        {
                            chartType="S",
                            controlConfig = new ControlConfig()
                            {
                                limitType =  s.ControlLimitType,
                                cl= s.CL,
                                lcl=  s.LCL,
                                ucl=  s.UCL,
                                clDisable= false,
                                lclDisable= false,
                                uclDisable= false
                            },
                            specConfig = new SpecConfig()
                            {
                                limitType = s.SpecLimitType ,
                                target = s.Target,
                                lsl= s.LSL,
                                usl= s.USL,
                                lslDisable= false,
                                targetDisable= false,
                                uslDisable=false,
                            },
                            screenConfig = screenConfig,
                              warningLimit =s.WarningLimit,
                        },
                    },
            };

            var ruleHoldAction = new List<RuleHoldActionItem>()
            {
                new RuleHoldActionItem() { equip="", holdAction = true, holdType="Hold Lot", caId = 301, }
            };

            var chartType = new ChartType()
            {
                XBAR = false,
                TREND = false,
                R = false,
                S = false
            };
            jobAddDto.ruleConfigInfo = new List<RuleConfigInfoItem>();
            foreach (var item in ruleEntities)
            {
                jobAddDto.ruleConfigInfo.Add(new RuleConfigInfoItem()
                {
                    chartType = chartType,
                    ruleObjectId = item.ID,
                    ruleCode = item.RULE_CODE,
                });

                // 要做校验
                if (item.CheckRule && item.RULE_CODE == "OOS")
                {
                    jobAddDto.ruleConfigInfo.Add(new RuleConfigInfoItem()
                    {
                        chartType = new ChartType()
                        {
                            XBAR = true,
                            TREND = false,
                            R = true,
                            S = true
                        },
                        ruleHoldAction = ruleHoldAction,
                        ruleObjectId = item.ID,
                        actionSwitch = true,
                        ocapFlowList = new List<string>(),
                        ruleCode = "OOS",
                    });
                }
                else if (item.CheckRule && item.RULE_CODE == "OOW")
                {
                    jobAddDto.ruleConfigInfo.Add(new RuleConfigInfoItem()
                    {
                        chartType = new ChartType()
                        {
                            XBAR = true,
                            TREND = true,
                            R = true,
                            S = true
                        },
                        ruleHoldAction = ruleHoldAction,
                        ruleObjectId = item.ID,
                        actionSwitch = true,
                        ocapFlowList = new List<string>(),
                        ruleCode = "OOW",
                    });
                }
                else if (item.CheckRule && item.RULE_CODE == "SOOS")
                {
                    jobAddDto.ruleConfigInfo.Add(new RuleConfigInfoItem()
                    {
                        chartType = new ChartType()
                        {
                            XBAR = false,
                            TREND = true,
                            R = false,
                            S = false
                        },
                        ruleHoldAction = ruleHoldAction,
                        ruleObjectId = item.ID,
                        actionSwitch = true,
                        ocapFlowList = new List<string>(),
                        ruleCode = "SOOS",
                    });
                }
                else if (item.CheckRule && item.RULE_CODE == "SOOW")
                {
                    jobAddDto.ruleConfigInfo.Add(new RuleConfigInfoItem()
                    {
                        chartType = new ChartType()
                        {
                            XBAR = false,
                            TREND = true,
                            R = false,
                            S = false
                        },
                        ruleHoldAction = ruleHoldAction,
                        ruleObjectId = item.ID,
                        actionSwitch = true,
                        ocapFlowList = new List<string>(),
                        ruleCode = "SOOW",
                    });
                }
                else if (item.CheckRule && item.RULE_CODE == "WE1")
                {
                    jobAddDto.ruleConfigInfo.Add(new RuleConfigInfoItem()
                    {
                        chartType = new ChartType()
                        {
                            XBAR = true,
                            TREND = true,
                            R = true,
                            S = true
                        },
                        ruleHoldAction = ruleHoldAction,
                        ruleObjectId = item.ID,
                        actionSwitch = true,
                        ocapFlowList = new List<string>(),
                        ruleCode = "WE1",
                    });
                }
            }

            jobAddDto.spcCdfList = new List<SpcCdfListItem>()
            {
                    new SpcCdfListItem(){ seqNo =1, name = "Key Chart", value="KEY(Y)", dataType="String"}
            };


            jobAddDto.gradeAlarmList = new List<GradeAlarmListItem>()
            {
                new GradeAlarmListItem()
                {
                    id="",
                    alarmType="OOS",
                    alarmTools=new List<string>(){ "MAIL" },
                    alarmTo="95845",
                    alarmCc="14141",
                    alarmTemplateId=19063,
                    jobIdFlag=true
                },
                new GradeAlarmListItem()
                {
                    id="",
                    alarmType="OOC",
                    alarmTools=new List<string>(){ "MAIL" },
                    alarmTo="95845",
                    alarmCc="14141",
                    alarmTemplateId=19063,
                    jobIdFlag=true
                },
            };

            #endregion

            return jobAddDto;
        }

        private void SendSpcCheck()
        {

        }

    }

    public class ChartTypeLimit
    {
        public string USL { get; set; }
        public string Target { get; set; }
        public string LSL { get; set; }
        public string UCL { get; set; }
        public string CL { get; set; }
        public string LCL { get; set; }
        public string WarningLimit { get; set; }
        //  "Standard" : "MANUAL",
        public string ControlLimitType { get; set; }
        public string SpecLimitType { get; set; }
    }
}
